//
//  DataXmlParser.m
//  xKey Interface
//
//  Created by Guillaume SOURDRILLE on 19/02/12.
//  Copyright (c) 2012 Edenyorke. All rights reserved.
//

#import "DataXmlParser.h"
#import "URLConnection.h"
#import "Data.h"

@implementation DataXmlParser

- (NSXMLParser *)getRequest:(NSURL *)url {
    NSURLRequest* chRequest = [NSURLRequest requestWithURL:url cachePolicy: NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
    NSError* theError;
    NSData* response = [NSURLConnection sendSynchronousRequest:chRequest returningResponse:nil error:&theError];
    NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:response];
    return xmlParser;
}

-(NSMutableArray*) parseXmlFromUrl: (NSURL*) url{
    
    NSXMLParser *xmlParser;
    xmlParser = [self getRequest:url];
    donnes = [[NSMutableArray alloc] init];
    [xmlParser setDelegate:self];
    [xmlParser parse];
    return donnes;
    
}

-(NSMutableString*) launchGame: (NSURL*) url{
    NSXMLParser *xmlParser;
    xmlParser = [self getRequest:url];
    [xmlParser setDelegate:self];
    [xmlParser parse];
    return currentTraystate;
}



-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
 namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{ 
    currentElement = elementName;
    if ([elementName isEqualToString:@"ISO"])
    {
        NSLog(@"elment ISO trouvé: %@", elementName);
        items = [[NSMutableDictionary alloc] init];
        currentName = [[NSMutableString alloc] init];
        currentId = [[NSMutableString alloc] init];
    }else if ([elementName isEqualToString:@"TRAYSTATE"]){
         currentTraystate = [[NSMutableString alloc] init];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{  
    if ([elementName isEqualToString:@"ISO"]) {
       
        [items setObject:[currentName stringByReplacingOccurrencesOfString:@"\n" withString:@""] forKey:@"TITLE"];
        [items setObject:[currentId stringByReplacingOccurrencesOfString:@"\n" withString:@""]forKey:@"ID"];
        [donnes addObject:items];
       
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
    if ([currentElement isEqualToString:@"TITLE"]) 
    {
        [currentName appendString:string];
    } else if ([currentElement isEqualToString:@"ID"]) 
    {
        [currentId appendString:string];
    }  else if ([currentElement isEqualToString:@"TRAYSTATE"]) {
        [currentTraystate appendString:string];
    }
}


@end
